package com.itheima.web;

import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet", urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        getServletContext().setAttribute("count", 0);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext sc = getServletContext();
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        UserService userService = new UserServiceImpl();
        final String username = request.getParameter("username");
        final String password = request.getParameter("password");
        User user = new User(0, username, password);
        final boolean login = userService.isLogin(user);
        if (login) {
            int count = (int) sc.getAttribute("count");
            sc.setAttribute("count", ++count);
            response.getWriter().write("欢迎你:" + username + "登录,将在5秒后跳转！");
            response.setHeader("refresh", "5;url=" + sc.getContextPath() + "/JumpServlet");
        } else {
            response.sendRedirect(getServletContext().getContextPath() + "/register.html");
        }
    }
}
